<template>
  <div class="app-container">
    <el-container style="height: 760px; border: 1px solid #eee">
      <el-aside style="width: 460px;background-color: #ffffff">
        <div class="container" style="width: 100%;">
          <el-divider content-position="center">{{ editTitle }}</el-divider>
          <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="padding-left: 10px; padding-top: 15px;">
            <el-form-item label="名称" size="mini" prop="name" style="width: 325px;">
              <el-input v-model="addData.name"/>
            </el-form-item>
            <el-form-item label="标识" size="mini" prop="slug" style="width: 325px;">
              <el-input v-model="addData.slug" />
            </el-form-item>
            <el-form-item size="mini" label="上级" prop="pid" >
              <el-cascader
                style="width: 235px;"
                v-model="tmpSelectedPid"
                :props="{ checkStrictly: true }"
                placeholder="请选择分类"
                :options="parentSelectOptions"
                @change="handleParentChange"></el-cascader>
            </el-form-item>
            <el-form-item size="mini" label="方法" prop="http_method">
              <el-checkbox-group v-model="addMethodOptionTmp" @change="handleCheckedMethod">
                <el-checkbox v-for="m in methodOptions" :label="m" :key="m">{{m}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item size="mini" label="路由" prop="route" style="width: 325px;">
              <el-input v-model="addData.route"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button style="float: right; margin-right: 100px;" size="mini" type="primary" @click="handleAddSubmit()">提交</el-button>
            <el-button style="float: right; margin-right: 12px;" size="mini" v-waves type="primary" @click="resetQueryForm('addForm')">重置</el-button>
          </div>
        </div>
      </el-aside>
      <el-main>
        <div class="filter-container">
          <el-form ref="queryForm" :model="listQuery" :rules="queryRules" label-position="left">
            <el-form-item label="" prop="route" size="mini"  style="float: left;">
              <el-input v-model="listQuery.route" placeholder="请输入路由" class="filter-item" style="width: 120px;margin-right:5px;"></el-input>
            </el-form-item>
            <el-form-item label="" prop="title" size="mini" style="float: left;">
              <el-input v-model="listQuery.name" placeholder="请输入标题" class="filter-item" style="width: 120px;margin-right:5px;"></el-input>
            </el-form-item>
            <el-button v-waves class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
            <el-button v-waves class="filter-item" size="mini" type="danger" @click="resetQueryForm('queryForm')">重置</el-button>
          </el-form>
        </div>
        <el-table
          size="mini"
          v-loading="listLoading"
          :data="list"
          highlight-current-row
          row-key="Id"
          style="width: 100%"
          :tree-props="{ children: 'Children', hasChildren: true }"
        >
          <el-table-column align="left" label="ID" width="180px">
            <template slot-scope="{row}">
              <span>{{ row.Id }}</span>
            </template>
          </el-table-column>
          <el-table-column width="240px" align="left" label="名称">
            <template slot-scope="{row}">
              <span>{{ row.Name }}</span>
            </template>
          </el-table-column>

          <el-table-column width="170px" align="left" label="方法">
            <template slot-scope="{row}">
              <span>{{ row.HttpMethod }}</span>
            </template>
          </el-table-column>

          <el-table-column width="240px" align="left" label="路由">
            <template slot-scope="{row}">
              <span>{{ row.Route }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="{row}">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(row.Id)"
              >
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="handleDel(row.Id)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { adminPermissionList, adminPermissionAdd, adminPermissionDetail, adminPermissionDel } from '@/api/admin'
import waves from '@/directive/waves' // waves directive
import { delTreeEmptyChildren, isSubArray, strLength } from '@/utils/common'
import local from '@/lang/systems/admin_acl'

const methodOptions = ['GET', 'POST', 'OPTION']

export default {
  name: 'AdminPermissionList',
  components: { },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '禁用',
        '1': '启用'
      }
      return statusMap[status]
    }
  },
  data() {
    const checkName = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 名称不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 6) {
        return callback(new Error('对不起， 用户名长度为6-24个字符,汉字为3个字符!'))
      }

      const reg = /^[ _A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含汉字,数字,字母,下划线 空格'))
      } else {
        callback()
      }
    }
    const checkSlug = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 标识不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 6) {
        return callback(new Error('对不起， 用户名长度为6-24个字符!'))
      }

      const reg = /^[A-Za-z0-9_]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含数字,字母,下划线'))
      } else {
        callback()
      }
    }
    const checkMethod = function(rule, value, callback) {
      if (this.addData.pid === 0) {
        return callback()
      }

      if (!value) {
        return callback(new Error('对不起， 玩法不能为空!'))
      }

      const methods = value.split(',')
      if (!isSubArray(methods, methodOptions)) {
        callback(new Error('对不起, 无效的玩法'))
      } else {
        callback()
      }
    }
    const checkRoute = function(rule, value, callback) {
      if (this.addData.pid === 0) {
        return callback()
      }

      if (!value) {
        return callback(new Error('对不起， 非顶级权限，路由不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 64 || strLen < 6) {
        return callback(new Error('对不起， 用户名长度为6-64个字符!'))
      }

      const reg = /^[_A-Za-z0-9\-\/]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含数字,字母,下划线,反斜线,中横线'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      listLoading: true,
      listQuery: {
        page_index: 1,
        page_size: 10,
        route: '',
        name: ''
      },
      currentAction: 'add',
      addData: {
        id: 0,
        pid: '0',
        name: '',
        slug: '',
        http_method: '',
        route: ''
      },
      tmpSelectedPid: '0',
      parentSelectOptions: [],
      methodOptions: methodOptions,
      addMethodOptionTmp: [],
      editTitle: this.$t('admin_acl.window.add_window_title'),
      rules: {
        id: [],
        pid: [
          { required: true, message: '需要选择上级', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '需要填写名称', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        slug: [
          { required: true, message: '需要填写标识', trigger: 'blur' },
          { validator: checkSlug, trigger: 'blur' }
        ],
        http_method: [
          { validator: checkMethod.bind(this), trigger: 'blur' }
        ],
        route: [
          { validator: checkRoute.bind(this), trigger: 'blur' }
        ]
      },
      queryRules: {
        title: [
          { required: false, message: '需要填写标题', trigger: 'blur' }
        ],
        route: [
          { required: false, message: '需要填写路由', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    if (!this.$i18n.getLocaleMessage('en')['admin_acl']) {
      this.$i18n.mergeLocaleMessage('en', local.en)
      this.$i18n.mergeLocaleMessage('zh', local.zh)
    }
  },
  methods: {
    resetAddData() {
      this.addMethodOptionTmp = []
      this.tmpSelectedPid = '0'
      this.addData = {
        id: 0,
        pid: 0,
        name: '',
        http_method: '',
        slug: '',
        route: ''
      }
    },
    resetQueryData() {
      this.listQuery = {
        page_index: 1,
        page_size: 10,
        route: '',
        name: ''
      }
    },
    getList() {
      this.listLoading = true
      adminPermissionList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.data
          this.listLoading = false
          setTimeout(() => {
            this.listLoading = false
            this.getDetail(0)
          }, 200)
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        }
      })
    },
    getDetail(id) {
      this.resetAddData()
      adminPermissionDetail(id).then((response) => {
        if (response.success) {
          this.parentSelectOptions = delTreeEmptyChildren(response.data.parent_select_options)
          console.log(this.parentSelectOptions)
          this.parentSelectOptions.unshift({ value: '0', label: '--顶级权限--', children: [] })
          if (id > 0) {
            this.addData = response.data.item
            // HTTP方法
            if (response.data.item.http_method) {
              this.addMethodOptionTmp = response.data.item.http_method.split(',')
            }
            // 上级
            if (response.data.item.pid) {
              this.tmpSelectedPid = response.data.item.pid
            }

            this.editTitle = this.$t('admin_acl.window.edit_window_title') + ' - ' + id
          }
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      })
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleEdit(id) {
      this.resetAddData()
      this.getDetail(id)
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleAddSubmit() {
      this.addData.http_method = this.addMethodOptionTmp.join(',')
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          adminPermissionAdd(this.addData).then((response) => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '添加权限成功'
              })
              this.getList()
              this.resetAddData()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleCheckedMethod(val) {
      this.addMethodOptionTmp = val
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除权限,并删除角色已分配,用户已分配, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminPermissionDel(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetQueryForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleParentChange(item) {
      if (item.length > 0) {
        this.addData.pid = item[item.length - 1]
      }
    }
  }
}
</script>
